var request = require('superagent')

export default {
    Get(url){
        return new Promise((resolve,reject)=>{
                request.get(url)
                .then((response)=>{
                if(response.statusCode===200){
                    let result= this.String2Object(response.text);
                    resolve(result);
                }
                else{
                    reject(response);
                }
            });
        });
    },
    Post(url,dataObj){
        return new Promise((resolve,reject)=>{
            request.post(url)
            // .set('Content-Type', 'application/json')
            // .send(JSON.stringify(dataObj))
            .send(dataObj)
            .set('Content-Type', 'application/x-www-form-urlencoded')
            .then((response)=>{
                if(response.statusCode===200){
                    let result= this.String2Object(response.text);
                    if(result.code==="0")
                    {
                        resolve(result);
                    }
                    else{
                        reject(result);
                    }
                }
                else{
                    reject(response);
                }
            })
        });
    }, 
    PostWithFile(url,data,files){

        return new Promise((resolve,reject)=>{
            let req=request.post(url);
            
            //添加需要的字段
            data.forEach(i => {
                req.field(i[0],i[1]);
            });

            //添加图片
            files.forEach(i => {
                //name,path
                // console.log(i[1])
                req.attach(i[0], i[1]);
            });
            
            req.then((response)=>{
                if(response.statusCode===200){
                    let result= this.String2Object(response.text);
                    if(result.code==="0")
                    {
                        resolve(result);
                    }
                    else{
                        reject(result);
                    }
                }
                else{
                    reject(response);
                }
            })
        });
    }, 
    String2Object(strValue){
        let result=JSON.parse(strValue);
        return result;
    },

    GetResourceURL(url){
        return "http://39.100.3.34:8888"+url;
    }
}